import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { connect } from 'react-redux'
import { initCrossDomain } from '@/utils/cross-domain'
// import map from '@/utils/map'
// import { storeInfo,getViewByCityCode,getDefaultAreaInfo } from '@/api'
// 引入 WebView 组件
import { WebView, View } from '@tarojs/components'
import { loginMethod } from '@/utils/login'
import { pathQueryToJson } from '@/utils'
import { concatUrl } from '@/utils/index'
import { updateStore, setOpenLocation, updateCurrentLocation, updateCity } from '@/store/location/action'
const domain: string = `${BASE_H5_URL}/#`
type State = {
  webUrl: string,
  currentCar: ICar | {}
  userInfo: any,
  shareData: any,
  location: any
}
type paramsData = {
  carId?: string
  accessId?: string
  accessKey?: string
  userId?: number
  unionid?: string
  storeCode?: String
  serverTime?: number
  location?: any
  cityCode?: any
  areaCode?: any
	openId?:any
}
@connect<any>(({ location, car, user }) => ({ location, car, user }), _dispatch => ({
  dispatchStore(params) {
    return _dispatch(updateStore(params))
  },
  // 位置授权状态（true: 已开启，false: 未开启）
  dispatchOpenLocation(status) {
    return _dispatch(setOpenLocation(status))
  },
  dispatchCurrentLocation(params) {
    return _dispatch(updateCurrentLocation(params))
  },
  dispatchCity(params) {
    return _dispatch(updateCity(params))
  },
}))
class AppWebView extends Component<any> {
  $instance = getCurrentInstance();
  constructor (props) {
    super(props)
    const { carInfo } = this.props.car
    // console.log(this.props.user)
    const { userInfo } = this.props.user
    let currentCar = {}
    if (carInfo.currentCar) {
      currentCar = carInfo.currentCar
    }
    this.state = {
      webUrl: '',
      currentCar,
      userInfo,
      shareData: {},
      location: null
    }
  }

  state: State
  async UNSAFE_componentWillMount() {
    const { currentCar } = this.state
    this.setDataConfig(currentCar)
  }


  UNSAFE_componentWillReceiveProps(nextProps) {
    // let currentCar = nextProps.car.carInfo.currentCar
    // if (currentCar && currentCar.carLicense !== this.state.currentCar.carLicense) {
    //   this.setDataConfig(currentCar)
    // }
    // this.setDataConfig(currentCar)
    // Taro.startPullDownRefresh()
  }

  config = {
    navigationBarTitleText: '',
    enablePullDownRefresh: true
  }
  onShareAppMessage(res) {
    let { path, shareTitle, shareImgUrl, query } = this.$instance.router.params
    if (query) {
      // query = JSON.parse(query)
    } else {
      query = {
        shareTitle: ''
      }
    }
    let linkStoreCode = this.$instance.router.params.linkStoreCode
    let storeCode = linkStoreCode

    let copyParams = JSON.parse(JSON.stringify(this.$instance.router.params))
    if (copyParams.shareImgUrl) {
      delete copyParams.shareImgUrl
    }
    const newPath = concatUrl(`${this.$instance.router.path}?path=${path}`, copyParams)
    let shareData: any = {
      title: '',
      path: newPath
    }
    if (shareTitle) {
      shareData.title = shareTitle
    }
    if (shareImgUrl) {
      shareData.imageUrl = shareImgUrl
    }
    return shareData
  }

  handleMessage = (e) => {
    let { data } = e.detail
    if (data) {
			console.log('eeeee',e)
      console.log('分享带过来的数据123', data)
			// 需要区分是微信小程序还是支付宝小程序，微信小程序返回的datas回一个数组，支付宝小程序返回的data是一个对象
      // 专题登录返回
			if(Array.isArray(data)){ // 微信小程序
				data.forEach(async (val) => {
					if (val.BACK_ROUTE) {
						loginMethod()
					}
					if (val.linkStoreCode) { // 推荐下单门店编码
						Taro.setStorageSync('STORECODE', val.linkStoreCode)
					}
					if (val.storeCode) { // 推荐下单门店编码
						Taro.setStorageSync('STORECODE', val.storeCode)
					}
				})
				this.$instance.router.params = {
					...this.$instance.router.params,
					...data[0]
				}
			}else { // 支付宝小程序
				if (data.BACK_ROUTE) {
					loginMethod()
				}
				if (data.linkStoreCode) { // 推荐下单门店编码
					Taro.setStorageSync('STORECODE', data.linkStoreCode)
				}
				if (data.storeCode) { // 推荐下单门店编码
					Taro.setStorageSync('STORECODE', data.storeCode)
				}
				this.$instance.router.params = {
					...this.$instance.router.params,
					...data
				}
			}
    }
  }
  setDataConfig = (currentCar) => {
    const { userInfo } = this.state
    let { query, path, storeCode: linkStoreCode, scene } = this.$instance.router.params
		let openId = Taro.getStorageSync('IS_OPENID')
    if (scene) {
      let pageQuery = pathQueryToJson(decodeURIComponent(scene))
      path = pageQuery.path
      this.$instance.router.params = {
        ...this.$instance.router.params,
        ...pageQuery
      }
    }

    linkStoreCode = this.$instance.router.params.linkStoreCode
    let storeCode = linkStoreCode || Taro.getStorageSync('STORECODE') || ''
    if (query) {
      query = JSON.parse(query)
    }
    let herf = concatUrl(`${domain}${path}`, this.$instance.router.params)
    let data: paramsData = {}
    if (userInfo.accessId) {
      data = {
        accessId: userInfo.accessId,
        accessKey: userInfo.accessKey,
        storeCode,
        userId: userInfo.userId,
        unionid: userInfo.unionid,
        serverTime: userInfo.serverTime,
        cityCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').adCode : '',
        areaCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').districtCode : '',
				openId:openId ? openId : ''
      }
      if (currentCar) {
        data = {
          ...data,
          carId: currentCar.id
        }
      }
    } else {
      data = {
        storeCode
      }
    }
    console.log('data: ', data);
    let url = initCrossDomain({
      url: herf,
      data: data
    })
    this.setState({
      webUrl: url
    })
  }
  render() {
    const { webUrl } = this.state
    if (!webUrl) return null
    console.log('webUrl---: ', webUrl);
    return (
      <View>
        {webUrl ? <WebView src={webUrl} onMessage={this.handleMessage} /> : null}
      </View>
    )
  }
}
export default AppWebView
